package com.ljd.server.config.security;

import com.ljd.server.pojo.Menu;
import com.ljd.server.pojo.Role;
import com.ljd.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 根据请求分析请求url所需的角色
 *
 * @author ljd on 2022/1/24
 * @PACKAGE_NAME: com.ljd.server.config.security
 * @PROJECT_NAME: yeb
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IMenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        // 获取请求对应的角色信息
        List<Menu> menus = menuService.getMenusWithRole();
        for (Menu menu: menus) {
            // 判断请求url与菜单角色是否匹配
            if(antPathMatcher.match(menu.getUrl(),requestUrl)) {
                // 使用steam流获取角色列表中所有角色名称并封装成一个String数组
                String[] array = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                // 如果匹配,就将请求中的角色添加到securityConfig中,方便获取并判断
                return SecurityConfig.createList(array);
            }
        }
        // 如果请求url和所有的url都不匹配,就返回一个角色,这个角色代表你需要登录
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
